'use strict';
const  path =  require('path');
const  fs =  require('fs');
const util = require('../util/util') 
const Controller = require('./base');
const awaitWriteStream = require('await-stream-ready').write
const sendToWormhole = require('stream-wormhole')

/**
 * @controller User
 */
 class UserController extends Controller { 
  async login() { 
    const { ctx ,app} = this;
    let { name,password } = util.args(this.ctx);   
    const data = await this.app.mysql.get('user', { name,password }); 
    console.log( data )
    const token ='Bearer ' + app.jwt.sign( { username:name,  data:data } , this.app.config.jwt.secret);
    this.ctx.session.token = token
    this.success({data,token})
  }
 
  async update() {  // 检查token 居然需要两个
    if(this.check()) return;  
    let { phone,id,username, } = util.args(this.ctx);  
    console.log(phone,id)
    if(!id) return this.error("id不存在")
    const user = await this.app.mysql.get('user', {  id }); 
    console.log(user)
    if(!user) return this.error("用户不存在")
    
    var update = { phone,username,id}
    const data = await this.updateInfo(update);


    this.success(phone) 
 }
 async updateInfo(parms) {    // 注意 组装 需要更新的数据 过滤
    let { phone,id,username, email} = parms;  
    var update = {  }
    if(phone!=null &&  phone !='') update.phone = phone;
    if(username!=null &&  username !='') update.username = username;
    if(email!=null &&  email !='') update.email = email;
    console.log(update)
    const data = await this.app.mysql.update('user',update,{ where:{ id:parms.id }})
    return data; 
}

async logout() { 
   this.ctx.session = null;
   this.success("已登出")
}


  async register() { 
     const { ctx } = this;
     let { name,phone,password,code,email} = util.args(this.ctx);   
      
     // 验证code 有效 
     if(ctx.session.register_code ==null  || code == null )   return this.error('请输入验证码')
     if(ctx.session.register_code != code )   return this.error('验证码错误')

     // 查唯一
     const user = await this.app.mysql.get('user', { phone,password }); 
     console.log(user)
     if(user)  return this.error('账户已存在')
     
     // 密码加密

     let data = await this.app.mysql.insert('user',{  
       name,
       phone,
       password,
       email,
     })
     this.success(data)
 
  }

 
  async getcode1(){ // https://blog.csdn.net/qq_39081974/article/details/81084933
    const { ctx } = this;
    const svgCaptcha = require('svg-captcha');
    const options = {size:6,  width: 100, height: 40, fontSize: 50, color: true,  noise: 4, }
    const Captcha = svgCaptcha.createMathExpr(options);   
    console.log(`Captcha.text = ${Captcha.text }`)
    const {type, t} = ctx.query 
    if (type === '1') { 
      ctx.session.login_code = Captcha.text 
    } else {  c
      tx.session.register_code = Captcha.text
    } 
    ctx.session.maxAge = 1000 * 60 * 10
    ctx.body = { status: 0, message: 'success', data: Captcha.data }  // 一个SVG
  }
  async getcode(){ // https://www.cnblogs.com/bling/p/5618339.html
    const { ctx } = this;
    const captchapng = require('captchapng'); 
    var code = '0123456789';  // abcdefghijklmnopqrstuvwxyz 不能有字母
    var randomcode = '';
    for (var i = 0; i < 4; i++) {
        randomcode += code[parseInt(Math.random() * 1000) % code.length];
    }
    console.log(randomcode)

    const {type, t} = ctx.query 
    if (type === '1') { 
      ctx.session.login_code =  randomcode
    } else {  
      ctx.session.register_code = randomcode
    } 

    ctx.session.maxAge = 1000 * 60 * 10

    var p = new captchapng(80,30,parseInt(randomcode)); // width,height,numeric captcha
    p.color(255, 255, 255, 0);   
    p.color(80, 80, 80, 255);   
    ctx.set('content-type','image/jpeg')
    ctx.body = new Buffer( p.getBase64(),'base64');
    
    
  }
  async upload() { 
      const stream = await this.ctx.getFileStream();  
      const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
      const target = path.join(this.config.baseDir,'app/public/upload',filename);
      const writeStream = fs.createWriteStream(target); 
      let avatar = '';
      try { 
        await awaitWriteStream(stream.pipe(writeStream)); // 异步把文件流 写入
        avatar = "http://" + this.app.config.cluster.listen.hostname + ':' + this.app.config.cluster.listen.port + this.config.static.prefix + 'upload/' + filename;
        console.log(this.config.static.prefix)
        console.log(avatar)
    } catch (err) { 
        await sendToWormhole(stream); // 如果出现错误，则关闭管道
        this.ctx.status = 500;
        this.ctx.body = { msg: '未知错误！' }
        throw err;
    }
    this.ctx.status = 200; 
    this.ctx.body = { msg: '上传成功！', avatar } 
 
  }
  
}
module.exports =  UserController
 
 
